<template>
	<div>
		<el-button type="primary" mb-1 @click="downloadCsvTemplate">下载模板</el-button>
		<el-upload v-model:file-list="fileList" accept=".csv" :before-upload="handleBeforeUpload" :on-change="handleChange" :auto-upload="false">
			<el-button type="primary">Click to upload</el-button>
		</el-upload>
	</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

import type { UploadProps, UploadRawFile, UploadUserFile } from 'element-plus';

const fileList = ref<UploadUserFile[]>([]);

const snList = ref<string[]>([]);

const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
	const isCsv = file.type === 'text/csv' || file.name.endsWith('.csv');
	if (!isCsv) {
		ElMessage.error('只能上传 CSV 格式的文件!');
	}
	return isCsv;
};

/**
 * @function
 * @todo 文件改变时触发
 * @param { UploadRawFile } file 文件对象
 **/
const handleChange: UploadProps['onChange'] = (file) => {
	console.log('🚀 ~ uploadFile:', file.raw);
	readCsvFile(file.raw);
};

/**
 * @function
 * @todo 读取csv文件
 **/
const readCsvFile = (file: UploadRawFile | undefined) => {
	if (!file) return;
	const reader = new FileReader();
	reader.onload = (event) => {
		const content = event.target!.result;
		parseCsvContent(content);
	};
	reader.readAsText(file, 'UTF-8');
};

const parseCsvContent = (content) => {
	console.log('🚀 ~ parseCsvContent ~ content:', content);
	const lines = content.split('\n');
	const headers = lines[0].split(',').map((header) => header.trim());
	console.log('🚀 ~ parseCsvContent ~ headers:', headers);
	// 获取 sn 字段的索引
	const snIndex = headers.indexOf('设备sn');
	if (snIndex === -1) {
		ElMessage.error('No "设备sn" field found in the CSV.');
		return;
	}
	// 提取 sn 字段的内容
	snList.value = lines
		.slice(1)
		.map((line) => {
			const columns = line.split(',').map((col) => col.trim());
			return columns[snIndex];
		})
		.filter((sn) => sn)
		.join(','); // 过滤掉空值

	console.log('snList---', snList.value);
};

function downloadCsvTemplate() {
	// 创建 CSV 数据
	const csvData = [['设备sn'], ['qqq'], ['qsss'], ['ddd']];
	// 转换为 CSV 格式
	const csvContent = csvData.map((e) => e.join(',')).join('\n');
	// 以支持 UTF-8 编码
	const csvWithBOM = '\uFEFF' + csvContent;
	const blob = new Blob([csvWithBOM], { type: 'text/csv;charset=utf-8;' });
	const link = document.createElement('a');
	const url = URL.createObjectURL(blob);
	link.setAttribute('href', url);
	link.setAttribute('download', '设备sn模板.csv');
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
	URL.revokeObjectURL(url); // 释放 Blob URL
}
</script>
